package cn.hd01.web.auth;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hd01.repository.entity.WXApp;
import cn.hd01.repository.entity.WXOauth;
import cn.hd01.service.WXAppService;
import cn.hd01.service.WXOauthService;
import cn.hd01.web.config.WeChatDevConfig;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebHelper;
import cn.hd01.weixin.WeixinRequirementController;

import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;

@Component
public class WeChatAuthenticator implements Authenticator {

	private static final Logger logger = LoggerFactory.getLogger(WeixinRequirementController.class);

	@Autowired
	private WXAppService appService;

	@Autowired
	private WXOauthService woService;

	@Autowired
	private WeChatDevConfig config;

	@Override
	public boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (WebHelper.currentWXOauth() != null) {
			return true;
		}

		if (config.getEnable()) {
			logger.info("wechat dev mode");
			WXOauth wo = woService.findByWeixinIdAndOpenId(config.getWeixinId(), config.getOpenId());
			if (wo == null) {
				logger.info("cannot find dev wechat user");
				return false;
			}

			WebHelper.session().setAttribute(WebConstant.USER_SESSION_NAME, wo);
			return true;
		}

		logger.info("wechat product mode");
		String domain = request.getParameter("domain");
		if (!StringUtils.hasText(domain)) {
			response.sendError(HttpStatus.NOT_FOUND.value());
			return false;
		}

		WXApp app = appService.findByDomain(domain);
		if (app == null) {
			response.sendError(HttpStatus.NOT_FOUND.value());
			return false;
		}

		OauthAPI api = new OauthAPI(appService.getApiConfig(app));
		String code = WebHelper.basePath() + "/weixin/code/" + domain;
		String oauthUrl = api.getOauthPageUrl(code, OauthScope.SNSAPI_USERINFO,
				URLEncoder.encode(WebHelper.fullUrl(), "UTF-8"));

		response.sendRedirect(oauthUrl);
		return false;
	}

	@Override
	public AuthType type() {
		return AuthType.WECHAT;
	}

}
